// /src/utils/logsUtil.js
const fs = require('fs');
const path = require('path');

// 日志级别
const validLevels = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
const levelPriority = {
  trace: 0,
  debug: 1,
  info: 2,
  warn: 3,
  error: 4,
  fatal: 5,
};

// 获取根路径（适配 pkg）
function getRootPath() {
  return process.cwd();
}

const projectRoot = getRootPath();
const logDirectory1 = path.join(projectRoot, 'logs'); // logs/年/月/日/level/年-月-日_level.log
const logDirectory2 = path.join(projectRoot, 'logs2');

// 确保目录存在
function ensureDirectoryExists(directory) {
  try {
    fs.mkdirSync(directory, { recursive: true });
  } catch (err) {
    console.error(`创建目录失败: ${err}`);
  }
}

// 获取本地时间字符串（格式：YYYY-MM-DDTHH:mm:ss.sss）
function getLocalISOString(date) {
  const offset = date.getTimezoneOffset(); // 分钟数
  const localDate = new Date(date.getTime() - offset * 60 * 1000); // 转成本地时间的 UTC 时间
  return localDate.toISOString().replace('T', ' ').replace('Z', '');
}

// 构建日志路径
function buildLogPath(logDirectory, level, date) {
  const year = String(date.getFullYear());
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始
  const day = String(date.getDate()).padStart(2, '0');
  const dateStr = `${year}-${month}-${day}`;

  // 区分 log 和 log2
  if (logDirectory.includes('logs2')) {
    // logs2/info/2025/01/2025-01-01_info.log
    return path.join(logDirectory, level, year, month, `${dateStr}_${level}.log`);
  } else {
    // logs/2025/01/01/2025-01-01_info.log
    return path.join(logDirectory, year, month, day, `${dateStr}_${level}.log`);
  }
}

// 获取日志级别（支持首字母匹配）
function matchLogLevel(inputLevel) {
  if (validLevels.includes(inputLevel)) return inputLevel;

  const firstChar = inputLevel?.charAt(0).toLowerCase();
  for (const level of validLevels) {
    if (level.charAt(0) === firstChar) {
      return level;
    }
  }

  return 'info'; // 默认
}

// 构建 logger 实例
function createLoggerInstance(baseDir) {
  return new Proxy(
    {},
    {
      get(target, level) {
        if (!validLevels.includes(level)) {
          level = matchLogLevel(level);
        }

        const currentLevelPriority = levelPriority[level];
        const envLevel = process.env.LOG_LEVEL?.toLowerCase();
        const envLevelPriority = levelPriority[envLevel] ?? 0;

        if (currentLevelPriority < envLevelPriority) {
          return () => { }; // 级别不够，不输出
        }

        return (...messages) => {
          const now = new Date();
          const logFilePath = buildLogPath(baseDir, level, now);
          ensureDirectoryExists(path.dirname(logFilePath));

          const formattedMessages = messages.map(msg => {
            if (typeof msg === 'string') return msg;
            if (msg === null || msg === undefined) return String(msg);
            try {
              return JSON.stringify(msg, null, 2);
            } catch (err) {
              return msg.toString();
            }
          });

          const logContent = `${getLocalISOString(now)} - ${formattedMessages.join(' ')}\n`;
          try {
            fs.appendFileSync(logFilePath, logContent);
          } catch (err) {
            console.error(`写入日志文件失败: ${err}`);
          }
        };
      },
    }
  );
}

// 创建两个日志实例
const log = createLoggerInstance(logDirectory1);
const log2 = createLoggerInstance(logDirectory2);

module.exports = { log, log2 };